package com.echo.servlet.CategoryServlet;

import com.echo.entity.Category;
import com.echo.service.CategoryService;
import com.echo.service.ArticleCategoryRelationService;
import com.echo.servlet.BaseServlet;
// 使用System.out代替Logger以减少依赖

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 分类Servlet，处理分类相关的HTTP请求
 */
public class CategoryServlet extends BaseServlet {
    // 移除Logger，使用System.out输出调试信息
    private CategoryService categoryService = new CategoryService();
    private ArticleCategoryRelationService relationService = new ArticleCategoryRelationService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        setRequestEncoding(request);
        
        // 获取操作类型
        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }
        
        System.out.println("处理分类请求，操作类型: " + action);
        
        switch (action) {
            case "list":
                listCategories(request, response);
                break;
            case "addPage":
                // 检查是否是管理员，只有管理员可以添加分类
                if (checkAdmin(request, response)) {
                    showAddPage(request, response);
                }
                break;
            case "editPage":
                // 检查是否是管理员，只有管理员可以编辑分类
                if (checkAdmin(request, response)) {
                    showEditPage(request, response);
                }
                break;
            case "delete":
                // 检查是否是管理员，只有管理员可以删除分类
                if (checkAdmin(request, response)) {
                    deleteCategory(request, response);
                }
                break;
            default:
                listCategories(request, response);
                break;
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        setRequestEncoding(request);
        
        // 获取操作类型
        String action = request.getParameter("action");
        if (action == null) {
            response.sendRedirect(request.getContextPath() + "/category?action=list");
            return;
        }
        
        System.out.println("处理分类POST请求，操作类型: " + action);
        
        switch (action) {
            case "add":
                // 检查是否是管理员，只有管理员可以添加分类
                if (checkAdmin(request, response)) {
                    addCategory(request, response);
                }
                break;
            case "edit":
                // 检查是否是管理员，只有管理员可以编辑分类
                if (checkAdmin(request, response)) {
                    editCategory(request, response);
                }
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/category?action=list");
                break;
        }
    }
    
    /**
     * 显示分类列表
     */
    private void listCategories(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Category> categories = categoryService.getAllCategories();
            request.setAttribute("categories", categories);
            forward(request, response, "/admin/categoryList.html");
        } catch (Exception e) {
            System.out.println("显示分类列表失败: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "获取分类列表失败，请稍后重试");
            forward(request, response, "/admin/categoryList.html");
        }
    }
    
    /**
     * 显示添加分类页面
     */
    private void showAddPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 管理员权限已在调用处检查，这里直接执行
        
        try {
            // 数据库表结构不支持父分类，移除相关代码
            forward(request, response, "/admin/categoryAdd.html");
        } catch (Exception e) {
            System.out.println("显示添加分类页面失败: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "加载页面失败，请稍后重试");
            forward(request, response, "/admin/categoryAdd.html");
        }
    }
    
    /**
     * 添加分类
     */
    private void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("[SERVLET DEBUG] 进入addCategory方法");
        // 管理员权限已在调用处检查，这里直接执行
        
        try {
            // 获取表单数据
            String categoryName = request.getParameter("categoryName");
            String categoryDesc = request.getParameter("categoryDesc");
            String parentIdStr = request.getParameter("parentId");
            String sortOrderStr = request.getParameter("sortOrder");
            
            System.out.println("[SERVLET DEBUG] 获取到的表单参数：");
            System.out.println("[SERVLET DEBUG] categoryName = " + categoryName);
            System.out.println("[SERVLET DEBUG] categoryDesc = " + categoryDesc);
            System.out.println("[SERVLET DEBUG] parentIdStr = " + parentIdStr);
            System.out.println("[SERVLET DEBUG] sortOrderStr = " + sortOrderStr);
            
            // 验证必填项
            if (categoryName == null || categoryName.trim().isEmpty()) {
                System.out.println("[SERVLET DEBUG] 分类名称为空，返回错误");
                request.setAttribute("errorMsg", "分类名称不能为空");
                forward(request, response, "/categoryAdd.html");
                return;
            }
            
            // 创建分类对象
            Category category = new Category();
            category.setCategoryName(categoryName.trim());
            category.setCategoryDesc(categoryDesc != null ? categoryDesc.trim() : "");
            System.out.println("[SERVLET DEBUG] 创建Category对象：");
            System.out.println("[SERVLET DEBUG] - categoryName: " + category.getCategoryName());
            System.out.println("[SERVLET DEBUG] - categoryDesc: " + category.getCategoryDesc());
            
            // 调用服务层添加分类
            System.out.println("[SERVLET DEBUG] 调用categoryService.addCategory()方法");
            int categoryId = categoryService.addCategory(category);
            System.out.println("[SERVLET DEBUG] categoryService.addCategory()返回值: " + categoryId);
            
            if (categoryId > 0) {
                // 添加成功，重定向到分类列表
            System.out.println("[SERVLET DEBUG] 分类添加成功，准备重定向到列表页面");
            request.getSession().setAttribute("successMsg", "分类添加成功");
            response.sendRedirect(request.getContextPath() + "/category?action=list");
        } else if (categoryId == -1) {
            // 分类名称已存在
            System.out.println("[SERVLET DEBUG] 分类名称已存在，返回错误信息");
            request.setAttribute("errorMsg", "分类名称已存在，请使用其他名称");
            forward(request, response, "/admin/categoryAdd.html");
        } else {
            // 添加失败
            System.out.println("[SERVLET DEBUG] 分类添加失败，返回错误信息");
            request.setAttribute("errorMsg", "分类添加失败，请稍后重试");
            forward(request, response, "/admin/categoryAdd.html");
        }
        } catch (NumberFormatException e) {
            System.out.println("[SERVLET DEBUG] 捕获NumberFormatException异常");
            System.out.println("[SERVLET DEBUG] 异常信息: " + e.getMessage());
            System.out.println("[SERVLET DEBUG] 异常类型: " + e.getClass().getName());
            e.printStackTrace();
            request.setAttribute("errorMsg", "参数格式错误，请检查输入");
                forward(request, response, "/admin/categoryAdd.html");
        } catch (Exception e) {
            System.out.println("[SERVLET DEBUG] 捕获通用Exception异常");
            System.out.println("[SERVLET DEBUG] 异常信息: " + e.getMessage());
            System.out.println("[SERVLET DEBUG] 异常类型: " + e.getClass().getName());
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统异常，请稍后重试");
                forward(request, response, "/admin/categoryAdd.html");
        }
        System.out.println("[SERVLET DEBUG] addCategory方法执行完毕");
    }
    
    /**
     * 显示编辑分类页面
     */
    private void showEditPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 管理员权限已在调用处检查，这里直接执行
        
        try {
            // 获取分类ID
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.isEmpty()) {
                request.setAttribute("errorMsg", "分类ID不能为空");
                response.sendRedirect(request.getContextPath() + "/category?action=list");
                return;
            }
            
            Integer categoryId = Integer.parseInt(idStr);
            
            // 获取分类信息
            Category category = categoryService.getCategoryById(categoryId);
            if (category == null) {
                request.setAttribute("errorMsg", "分类不存在");
                response.sendRedirect(request.getContextPath() + "/category?action=list");
                return;
            }
            
            // 设置属性
            request.setAttribute("category", category);
            // 数据库表结构不支持父分类，移除相关代码
            
            forward(request, response, "/admin/categoryAdd.html");
        } catch (NumberFormatException e) {
            System.out.println("显示编辑分类页面参数格式错误: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "参数格式错误");
            response.sendRedirect(request.getContextPath() + "/category?action=list");
        } catch (Exception e) {
            System.out.println("显示编辑分类页面异常: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "加载页面失败，请稍后重试");
            response.sendRedirect(request.getContextPath() + "/category?action=list");
        }
    }
    
    /**
     * 编辑分类
     */
    private void editCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 管理员权限已在调用处检查，这里直接执行
        
        try {
            // 获取表单数据
            String idStr = request.getParameter("id");
            String categoryName = request.getParameter("categoryName");
            String categoryDesc = request.getParameter("categoryDesc");
            String parentIdStr = request.getParameter("parentId");
            String sortOrderStr = request.getParameter("sortOrder");
            
            // 验证必填项
            if (idStr == null || idStr.isEmpty() || categoryName == null || categoryName.trim().isEmpty()) {
                request.setAttribute("errorMsg", "分类ID和名称不能为空");
                response.sendRedirect(request.getContextPath() + "/category?action=list");
                return;
            }
            
            Integer categoryId = Integer.parseInt(idStr);
            
            // 创建分类对象
            Category category = new Category();
            category.setCategoryId(categoryId);
            category.setCategoryName(categoryName.trim());
            category.setCategoryDesc(categoryDesc != null ? categoryDesc.trim() : "");
            
            // 调用服务层更新分类
            boolean success = categoryService.updateCategory(category);
            
            if (success) {
                // 更新成功
                request.getSession().setAttribute("successMsg", "分类更新成功");
                response.sendRedirect(request.getContextPath() + "/category?action=list");
            } else {
                // 更新失败
                Category existingCategory = categoryService.getCategoryById(categoryId);
                if (existingCategory == null) {
                    request.setAttribute("errorMsg", "分类不存在");
                    response.sendRedirect(request.getContextPath() + "/category?action=list");
                } else {
                    // 检查是否是名称重复
                    if (categoryService.isCategoryNameExists(categoryName.trim())) {
                        request.setAttribute("errorMsg", "分类名称已存在，请使用其他名称");
                    } else {
                        request.setAttribute("errorMsg", "分类更新失败，请稍后重试");
                    }
                    
                    request.setAttribute("category", category);
                    forward(request, response, "/admin/categoryAdd.html");
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("编辑分类参数格式错误: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "参数格式错误，请检查输入");
            response.sendRedirect(request.getContextPath() + "/category?action=list");
        } catch (Exception e) {
            System.out.println("编辑分类异常: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统异常，请稍后重试");
            response.sendRedirect(request.getContextPath() + "/category?action=list");
        }
    }
    
    /**
     * 删除分类
     */
    private void deleteCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 管理员权限已在调用处检查，这里直接执行
        
        try {
            // 获取分类ID
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.isEmpty()) {
                request.setAttribute("errorMsg", "分类ID不能为空");
                response.sendRedirect(request.getContextPath() + "/category?action=list");
                return;
            }
            
            Integer categoryId = Integer.parseInt(idStr);
            
            // 调用服务层删除分类
            boolean success = categoryService.deleteCategory(categoryId);
            
            if (success) {
                // 删除成功
                request.getSession().setAttribute("successMsg", "分类删除成功");
            } else {
                // 删除失败
                Category category = categoryService.getCategoryById(categoryId);
                if (category == null) {
                    request.setAttribute("errorMsg", "分类不存在");
                } else {
                    // 数据库表结构不支持子分类，直接检查是否有文章
                    if (relationService.hasArticles(categoryId)) {
                        request.setAttribute("errorMsg", "分类下有文章，无法删除");
                    } else {
                        request.setAttribute("errorMsg", "分类删除失败，请稍后重试");
                    }
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("删除分类参数格式错误: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "参数格式错误");
        } catch (Exception e) {
            System.out.println("删除分类异常: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统异常，请稍后重试");
        } finally {
            response.sendRedirect(request.getContextPath() + "/category?action=list");
        }
    }
}